import * as React from 'react';
import PropTypes from 'prop-types';
import Helmet from 'react-helmet';
import { useStaticQuery, graphql } from 'gatsby';

const DocumentTitle = ({ description, lang, meta, title }) => {
  const { site } = useStaticQuery(
    graphql`
      query {
        site {
          siteMetadata {
            title
            description
            author
          }
        }
      }
    `,
  );

  const metaDescription = description || site.siteMetadata.description;

  return (
    <Helmet
      htmlAttributes={{
        lang,
      }}
      title={title}
      titleTemplate={title}
      meta={[
        {
          name: 'viewport',
          content: `
            width=device-width, 
            initial-scale=1.0, 
            maximum-scale=1
          `
        },
        {
          name: `description`,
          content: metaDescription,
        },
      ].concat(meta)}
    />
  );
};

DocumentTitle.defaultProps = {
  lang: 'zh-CN',
  meta: [],
  description: ``,
};

DocumentTitle.propTypes = {
  description: PropTypes.string,
  lang: PropTypes.string,
  meta: PropTypes.arrayOf(PropTypes.object),
  title: PropTypes.string.isRequired,
};

export default React.memo(DocumentTitle);
